//
// Created by wyh on 2025-08-08 21:41.
//
#include <fstream>
#include <iostream>
#include <sstream>
#include "sys/stat.h"
#include "fs/file.h"

using namespace std;
using namespace wyh::fs;


File::File(const std::string &path)
{
    m_path = path; //todo
}

std::string File::path() const
{
    return m_path;
}

std::string File::dir() const
{
    if (m_path.empty())
    {
        return "";
    }

    char sep='/'; //todo
    size_t last = m_path.find_last_of(sep);
    if(last!=string::npos)
    {
        return m_path.substr(0, last);
    }
    return "";
}

bool File::create()
{
    //目标文件所在目录不存在的，则文件创建失败
    //todo
    ofstream ofs(m_path);

    return false;
}

bool File::remove()
{
    return unlink(m_path.c_str())==0;
}

bool File::rename(const string &path)
{
    int ret = ::rename(m_path.c_str(), path.c_str());
    if (ret != 0)
    {
        return false;
    }
    m_path = path;
    return true;
}

void File::clear()
{
    ofstream ofs(m_path, ios::out);
    ofs.flush();
    ofs.close();
}

bool File::exists() const
{
    ifstream ifs(m_path);

    return ifs.good();
}

bool File::copy(const string &path)
{
    ifstream ifs(m_path);
    if (ifs.fail())
    {
        return true;
    }

    //如果目标文件不存在，则创建目标文件
    //todo
    ofstream ofs(path);
    if (ofs.fail())
    {
        return false;
    }

    ofs<<ifs.rdbuf();
    ofs.flush();
    ofs.close();
    return true;
}

int File::line() const
{
    ifstream ifs(m_path);
    int line = 0;
    string data;
    while (getline(ifs, data))
    {
        line++;
    }
    return line;
}

long File::size() const
{
//    //第一种方式
//    ifstream ifs(m_path);
//    ifs.seekg(0, ios_base::end);
//
//    return (long)ifs.tellg();

struct stat info = {};
    if (stat(m_path.c_str(), &info) != 0)
    {
        cerr << "stat file error:" << m_path << endl;
        return 0;
    }
    return info.st_size;
}

time_t File::time() const
{
    struct stat info = {};
    if (stat(m_path.c_str(), &info) != 0)
    {
        cerr << "stat file error:" << m_path << endl;
        return 0;
    }
    return info.st_mtime;
}

std::string File::read() const
{
//    //方式一
//    ifstream ifs(m_path);
//    string data;
//    ostringstream  oss;
//    while (getline(ifs, data))
//    {
//        oss<<data;
//    }
//
//    return oss.str();

    //方式二
    ifstream ifs(m_path);
    ostringstream oss;
    oss<<ifs.rdbuf();
    return oss.str();
}

bool File::write(const string &data)
{
    ofstream ofs(m_path);
    if (!ofs.is_open())
    {
        return false;
    }

    ofs.write(data.c_str(), data.size());
    return true;
}


